package View;

import Dao.Blog;
import Dao.BlogDao;
import Dao.User;
import common.Util;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;

@WebServlet("/update")
public class UpdateServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String str = req.getParameter("blogId");
        if(str==null || "".equals(str)){
            resp.getWriter().write("<h3>博客Id不存在</h3>");
            return;
        }
        int blogId = Integer.parseInt(str);

        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(blogId);
        if(blog == null){
            resp.getWriter().write("<h3>博文不存在</h3>");
            return;
        }
        TemplateEngine engine = (TemplateEngine) getServletContext().getAttribute("engine");
        WebContext webContext = new WebContext(req,resp,getServletContext());
        webContext.setVariable("blog",blog);

        engine.process("alter",webContext,resp.getWriter());
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");

        User user = Util.checkLoginStatus(req);
        if(user == null){
            resp.sendRedirect("login.html");
            return;
        }

        // 1. 获取参数
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        String str = req.getParameter("blogId");
        if(str==null || "".equals(str)){
            System.out.println("blogId不存在");
            return;
        }
        int blogId = Integer.parseInt(str);
        // 2. 判断是否存在
        if(title==null || "".equals(title) || content==null || "".equals(content)){
            resp.getWriter().write("<h3>文章标题或者内容不存在</h3>");
            return;
        }

        // 插入到数据库中
        Blog blog = new Blog();
        blog.setContent(content);
        blog.setTitle(title);
        blog.setPostTime(new Timestamp(System.currentTimeMillis()));
        blog.setBlogId(blogId);
        BlogDao blogDao = new BlogDao();
        blogDao.update(blog);
        // 重定向
        resp.sendRedirect("personlist.html");
    }
}
